<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'process:fd:pmProjectSegmentation:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #pmProjectSplitNatureList>
        <BasicTable
          @register="registerPmProjectSplitNatureTable"
          @row-click="handlePmProjectSplitNatureRowClick"
          @edit-change="onEditChange"
        />
        <a-button
          class="mt-2"
          @click="handlePmProjectSplitNatureAdd"
          v-auth="'process:fd:pmProjectSegmentation:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="Flow_PmProjectSegmentation"
        completeText="提交"
        :loading="loadingRef"
        :auth="'process:fd:pmProjectSegmentation:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
    <ListSelect
      ref="fdlsit"
      v-show="false"
      selectType="natureSelect"
      :checkbox="true"
      :params="queryParams"
      :selectList="listSelectRef"
      @select="handSelect"
    />

    <ListSelect
      ref="fdbglsit"
      v-show="false"
      selectType="natureFdbgSelect"
      :checkbox="true"
      :params="queryParams2"
      :selectList="listSelectRef"
      @select="handSelect"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsProcessFdPmProjectSegmentationForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed, watch } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PmProjectSegmentation,
    pmProjectSegmentationSave,
    pmProjectSegmentationForm,
  } from '/@/api/process/fd/pmProjectSegmentation';
  import { BpmButton } from '/@/components/Bpm';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';
  import { ListSelect } from '/@/components/ListSelect';
  import { disable } from '/@/api/m8/machine/machine';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('process.fd.pmProjectSegmentation');
  const { showMessage } = useMessage();
  const record = ref<PmProjectSegmentation>({} as PmProjectSegmentation);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增分单') : t('编辑分单'),
  }));

  let listSelectRef = ref([]);
  let queryParams = ref({});
  let queryParams2 = ref({});

  let fdlsit = ref<any>('');
  let fdbglsit = ref<any>('');

  const loadingRef = ref(false);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('工程名称'),
      field: 'oldid',
      fieldLabel: 'projInfo.projectname',
      component: 'TreeSelect',
      componentProps: {
        api: pmProjectinformationTreeData,
        params: {
          projStatus: 2,
          treeOper: '12',
        },
        canSelectParent: false,
        allowClear: false,
        onChange: async (e) => {
          queryParams.value = {
            projectno: e,
          };
          let arr = await pmProjectSplitNatureTable.getDataSource();
          console.log(arr, '111');
          let arrNew = [...arr];
          arrNew.forEach(async (item, index) => {
            console.log(index);
            // console.log(item,'111');
            await pmProjectSplitNatureTable.deleteTableDataRecord(item);
            // console.log(item,'2222');
          });
        },
        disabled: computed(() => hasRelatedData.value),
        // 使用计算属性 isDisabled 设置 disabled
      },
      itemProps: { validateTrigger: 'blur' },
      required: true,
    },

    {
      label: t('工程编码'),
      field: 'oldid',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
      required: true,
    },
    {
      label: t('来源ID'),
      field: 'sourceId',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
      show: false,
    },
    // {
    //   label: t('生成新项目的ID'),
    //   field: 'childid',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 50,
    //     disabled: true,
    //   },
    //   show: false,
    // },
    {
      label: t('分单类型'),
      field: 'fdType',
      component: 'Select',
      componentProps: {
        dictType: 'zf_fd_type',
        allowClear: false,
        disabled: true,
      },
      required: true,
    },
    {
      label: t('分单名称'),
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        allowClear: true,
      },
    },
    {
      label: t('分单原因类型'),
      field: 'reasonid',
      component: 'Select',
      componentProps: {
        dictType: 'zf_fd_reason',
        allowClear: true,
      },
      required: true,
    },

    {
      label: t('分单原因'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 255,
      },
      required: true,
    },
    {
      label: t('新工程编号'),
      field: 'newpjno',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
    },
    {
      label: t('分单附件'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'ProjectSegmentation_image',
        uploadType: 'all',
      },
      colProps: { lg: 24, md: 24 },
      rules: [
        { required: true },
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              const len = !value || value['ProjectSegmentation_image__len'] || 0;
              if (len == 0) reject(t('请上传分单附件！'));
              else resolve();
            });
          },
        },
      ],
    },
    {
      label: t('分单水表'),
      field: 'pmProjectSplitNatureList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'pmProjectSplitNatureList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
    labelWidth: 150,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerPmProjectSplitNatureTable, pmProjectSplitNatureTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handlePmProjectSplitNatureDelete.bind(this, record),
          },
          auth: 'process:fd:pmProjectSegmentation:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setPmProjectSplitNatureTableData(_res: Recordable) {
    pmProjectSplitNatureTable.setColumns([
      {
        title: t('extId'),
        dataIndex: 'extId',
        width: 130,
        align: 'left',
        ifShow: false,
      },
      {
        title: t('oldQty'),
        dataIndex: 'oldQty',
        width: 130,
        align: 'left',
        ifShow: false,
      },
      {
        title: t('水表编号'),
        dataIndex: 'metercode',
        width: 130,
        align: 'left',
      },
      {
        title: t('水表名称'),
        dataIndex: 'metername',
        width: 130,
        align: 'left',
      },

      {
        title: t('性质编码'),
        dataIndex: 'naturecode',
        width: 130,
        align: 'left',
        ifShow: false,
      },
      {
        title: t('性质名称'),
        dataIndex: 'naturename',
        width: 130,
        align: 'left',
      },
      {
        title: t('水表口径'),
        dataIndex: 'caliber',
        width: 130,
        align: 'left',
      },
      {
        title: t('水表ID'),
        dataIndex: 'parentnatureid',
        width: 130,
        align: 'left',
        ifShow: false,
      },

      {
        title: t('加压等级编号'),
        dataIndex: 'pressuregradecode',
        width: 130,
        align: 'left',
        ifShow: false,
      },
      {
        title: t('加压等级名称'),
        dataIndex: 'pressuregradename',
        width: 130,
        align: 'left',
      },
      {
        title: t('DM分区'),
        dataIndex: 'dmapartition',
        width: 130,
        align: 'left',
      },
      {
        title: t('监测表'),
        dataIndex: 'ismonitor',
        width: 80,
        align: 'center',
        dictType: 'sys_yes_no',
      },
      {
        title: t('消防表'),
        dataIndex: 'isfirecontrol',
        width: 80,
        align: 'center',
        dictType: 'sys_yes_no',
      },
      {
        title: t('水表总数'),
        dataIndex: 'metercount',
        width: 130,
        align: 'center',
      },

      {
        title: t('剩余数量'),
        dataIndex: 'nature.remaining',
        width: 130,
        align: 'center',
      },
      {
        title: t('本次安装数'),
        dataIndex: 'splitedcount',
        width: 150,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 50,
          min: 0, // Ensure the minimum value is 0
          required: true, // Make the field required
        },
        editRule: true,
      },
    ]);
    pmProjectSplitNatureTable.setTableData(record.value.pmProjectSplitNatureList || []);
  }

  // 监听record.value.pmProjectSplitNatureList 值的变化
  const hasRelatedData = ref(false);
  watch(
    () => record.value.pmProjectSplitNatureList,
    (newVal) => {
      // console.log(newVal, 'newVal');
      if (newVal && newVal.length > 0) {
        hasRelatedData.value = true;
      } else {
        hasRelatedData.value = false;
      }
      if (record.value.fdType == '2') {
        hasRelatedData.value = true;
      }
    },
    { deep: true },
  );

  function handlePmProjectSplitNatureRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  async function handlePmProjectSplitNatureAdd() {
    // pmProjectSplitNatureTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
    if (!getFieldsValue().oldid) {
      showMessage('请先选择工程名称！');
      return;
    }
    listSelectRef.value = [];
    let arr = pmProjectSplitNatureTable.getDataSource().map((item) => {
      return item.parentnatureid;
    });
    queryParams.value.selIds = arr.join(',');
    queryParams2.value.selIds = arr.join(',');

    if (record.value.fdType == '2') {
      //变更
      fdbglsit.value.handleInputClick();
    } else {
      fdlsit.value.handleInputClick();
    }
  }

  async function handSelect(selectData) {
    selectData.forEach((item) => {
      // 判断 本次拆分数 不能大于剩余数量，默认是剩余数量
      if (item.remaining < item.splitedcount) {
        item.splitedcount = item.remaining;
      }
      pmProjectSplitNatureTable.insertTableDataRecord({
        ...item,
        editable: true,
        isNewRecord: true,
        parentnatureid: item.id,
        splitedcount: item.remaining,
        nature: {
          remaining: item.remaining,
        },
      });
    });
  }

  // async function handSelect(selectData) {
  //   let arr = await pmProjectSplitNatureTable.getDataSource();
  //   selectData.forEach((item) => {
  //     let flag = true;
  //     arr.forEach((res) => {
  //       if (res.parentnatureid == item.id) {
  //         flag = false;
  //       }
  //     });
  //     // 判断 本次拆分数 不能大于剩余数量，默认是剩余数量
  //     if (item.remaining < item.splitedcount) {
  //       item.splitedcount = item.remaining;
  //     }
  //     if (flag) {
  //       pmProjectSplitNatureTable.insertTableDataRecord({
  //         ...item,
  //         // id: new Date().getTime() + item.id,
  //         editable: true,
  //         isNewRecord: true,
  //         parentnatureid: item.id,
  //         splitedcount: item.remaining,
  //         nature: {
  //           remaining: item.remaining,
  //         },
  //         // extId: '111111111',
  //         // munit: item.unit,
  //         // iqty: item.num,
  //       });
  //     }
  //   });
  // }

  // async function handSelect2(selectData) {
  //   let arr = await pmProjectSplitNatureTable.getDataSource();
  //   selectData.forEach((item) => {
  //     let flag = true;
  //     arr.forEach((res) => {
  //       if (res.parentnatureid == item.id) {
  //         flag = false;
  //       }
  //     });
  //     // 判断 本次拆分数 不能大于剩余数量，默认是剩余数量
  //     if (item.remaining < item.splitedcount) {
  //       item.splitedcount = item.remaining;
  //     }
  //     if (flag) {
  //       pmProjectSplitNatureTable.insertTableDataRecord({
  //         ...item,
  //         // id: new Date().getTime() + item.id,
  //         editable: true,
  //         isNewRecord: true,
  //         parentnatureid: item.id,
  //         splitedcount: item.remaining,
  //         nature: {
  //           remaining: item.remaining,
  //         },
  //         // extId: '111111111',
  //         // munit: item.unit,
  //         // iqty: item.num,
  //       });
  //     }
  //   });
  // }

  function handlePmProjectSplitNatureDelete(record: Recordable) {
    pmProjectSplitNatureTable.deleteTableDataRecord(record);
  }

  async function getPmProjectSplitNatureList() {
    let pmProjectSplitNatureListValid = true;
    let pmProjectSplitNatureList: Recordable[] = [];
    for (const record of pmProjectSplitNatureTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        pmProjectSplitNatureListValid = false;
      }
      console.log(record, 'record===');
      pmProjectSplitNatureList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of pmProjectSplitNatureTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      pmProjectSplitNatureList.push({
        ...record,
        status: '1',
      });
    }
    if (!pmProjectSplitNatureListValid) {
      throw { errorFields: [{ name: ['pmProjectSplitNatureList'] }] };
    }
    return pmProjectSplitNatureList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmProjectSegmentationForm(data);
    record.value = (res.pmProjectSegmentation || {}) as PmProjectSegmentation;
    record.value.__t = new Date().getTime();
    queryParams.value = {
      projectno: record.value.oldid,
    };

    queryParams2.value = {
      oldid: record.value.oldid,
      newpjno: record.value.newpjno,
    };
    setFieldsValue(record.value);
    setPmProjectSplitNatureTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.pmProjectSplitNatureList = await getPmProjectSplitNatureList();
      data.pmProjectSplitNatureList.forEach((item) => {
        item.splitedcount = item.splitedcount ? item.splitedcount : '0';
      });
      // console.log('submit', params, data, record);
      const res = await pmProjectSegmentationSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }

  function onEditChange({ column, value, record }) {
    // 当同一行的单价或者数量发生变化时，更新合计金额（三个数据均为当前行编辑组件的值）
    if (column.dataIndex === 'splitedcount') {
      // 检查是否是本次拆分数字段
      const remaining = record.nature?.remaining; // 获取剩余数量

      if (value === '' || value > remaining) {
        // 检查是否为空或大于剩余数量
        // 如果不满足条件，显示错误提示并阻止变更
        // alert('本次拆分数必须填写且不能大于剩余数量');
        showMessage(t('本次拆分数必须填写且不能大于剩余数量'));
        return;
      }
    }
  }
</script>
